'use strict';

app.controller('mapCtrl', ['$scope','$http','loginService', function($scope,$http,loginService,uiGmapGoogleMapApi, uiGmapIsReady){
	
     //=====================paging groups nearby======================
    $scope.nbr_rows_groups=0;
    $scope.entryLimit_group = 10;
    $scope.offset_group = 0;
    $scope.disablePrev_group = true;
    $scope.disableNext_group = false;
    $scope.page_now_group = 1;
    //================================================================
	
	 //=====================paging events of group ======================
	$scope.nbr_rows_eg=0;
    $scope.entryLimit_eg = 5
    $scope.offset_eg = 0;
    $scope.disablePrev_eg = true;
    $scope.disableNext_eg = false;
    $scope.page_now_eg = 1;
    //================================================================
	
	$scope.search = function() {
		var rad=10;
		if($scope.radius.val==1)
			rad =10;
		else
			rad =50;
		$scope.searchGroupEventNearBy($scope.longtitude,$scope.latitude,rad,0,100);
		//$scope.getMap();
		//alert($scope.radius.val);
		
	}
	
	$scope.init = function() {
		     //$scope.gotoCurrentLocation();
	    	 loginService.islogged(); 
			 $scope.link = loginService.getLink();
			 $scope.latitude = loginService.getLat();
			 $scope.longtitude = loginService.getLon();
			 $scope.getMap();
			
			 //alert($scope.radius);
			      //=====================map combox filter===============================
		 $scope.filter_map = [{
		      "radius": "10 km",
		    	  "val": 1
		    }, 
		    { "radius": "50 km",
		    	"val": 2
		    }];
		 
		 $scope.selectedOption = $scope.filter_map[1];
		 
		//========================================================================
	     };
    

		 $scope.getMap = function(id){ 
	        	//$scope.latitude = 21.035265;
				//$scope.longtitude = 105.779548;
				$scope.cities = [];
				if($scope.latitude!=''&&$scope.longtitude!=''){
					$scope.cities.push({ 
							"name" : 'Current Location',
							"interest"  : 'This is your current location',
							"lat" : $scope.latitude,
							"long" : $scope.longtitude,
							"icon":"http://maps.google.com/mapfiles/ms/icons/blue-dot.png"
						});
				}
				 
				 
				 $scope.getGroupsEventsNearByInMap($scope.longtitude,$scope.latitude,10,0,100);
	 }
	 
	 
			 $scope.gotoCurrentLocation = function () {
			if ("geolocation" in navigator) {
				navigator.geolocation.getCurrentPosition(function (position) {
					var c = position.coords;
					//$scope.gotoLocation(c.latitude, c.longitude);
					//alert(c.latitude +' -  '+ c.longitude);
				});
				return true;
			}
			
		};
		
         $scope.searchGroupsEventsNearByInMap = function(lon, lat,rad,start,count){ 
				 $scope.configMap();
				
			        $http.get($scope.link+'nearbygroup/'+lon+'/'+lat+'/'+rad+'/'+start+'/'+count+'/').success(function(data){
			        	console.log('all group nearby is loaded');
			      
					  var i = 0;
					  var red_dot = "http://maps.google.com/mapfiles/ms/icons/red-dot.png";
					  var blue_dot = "http://maps.google.com/mapfiles/ms/icons/blue-dot.png";
					  angular.forEach(data.data,function(){
						var loc = data.data[i].location;
						var loc_Str = loc.toString();
						var arr  = loc_Str.split(",");
						
						var dot=red_dot;
						
						if($scope.name_group==data.data[i].name){
							dot=blue_dot;
						}
					    $scope.cities.push({ 
								"name" : data.data[i].name,
								"interest"  : data.data[i].interest,
								"lat" : arr[0],
								"long" : arr[1],
								"icon":dot
							});

					  i++;
					  })
					
					  alert(JSON.stringify($scope.cities));
					 
			        }).error(function(data, status, config) {
		        	console.log('can not load group nearby');
		           });
				  
				}		
	
	     $scope.getGroupsEventsNearByInMap = function(lon, lat,rad,start,count){ 
			$scope.configMap();
		 }
			 
		
		 $scope.searchGroupEventNearBy= function(lon,lat,rad,start,count){
		     $http.get($scope.link+'nearbygroup/'+lon+'/'+lat+'/'+rad+'/'+start+'/'+count+'/').success(function(data){
			         console.log('all groups nearby is loaded');
			         
					 $scope.nb_groups = data.data.length;
					 $scope.jsonToArray_groups(data);  
					 pageResult_group($scope);
					
					 if( ($scope.page_now_group==1)  &&  ($scope.nbr_rows_groups > $scope.entryLimit_group) )
					 { 
					   $scope.disableNext_group = false;
					 }
			        }).error(function(data, status, config) { 
					 alert('No groups found'); 
		        	console.log('can not load groups nearby');
		           });
			  $http.get($scope.link+'nearbyevent/'+lon+'/'+lat+'/'+rad+'/'+start+'/'+count+'/').success(function(data){
			         console.log('all events nearby is loaded');
			         alert(JSON.stringify(data));
					 $scope.nb_events = data.data.length;
					// $scope.jsonToArray_events(data);  
					 pageResult_group_event($scope);
					 if( ($scope.page_now_eg==1)  &&  ($scope.nbr_rows_eg > $scope.entryLimit_eg) )
						 {
						 $scope.disableNext_eg = false;
						 }
			        }).error(function(data, status, config) {  alert('No events found');
		        	console.log('can not load events nearby');
		           });
				   
			
		 }
		
		
		
		 $scope.jsonToArray_events = function (data) {
				$scope.d = new Array();
				var i = 0;
				angular.forEach(data.data,function(){
					$scope.d[i]=new Array(2);
		    		$scope.d[i][0] =  data.data[i].name;
					$scope.d[i][1] =  data.data[i].id;
		            i++;
		        })
		        $scope.nbr_rows_events = i ;
				
				$scope.d_ini= angular.copy($scope.d);
			}
		
		$scope.jsonToArray_groups = function (data) {
				$scope.b = new Array();
				var i = 0;
				angular.forEach(data.data,function(){
					$scope.b[i]=new Array(2);
		    		$scope.b[i][0] =  data.data[i].name;
					$scope.b[i][1] =  data.data[i].id;
		            i++;
		        })
		        $scope.nbr_rows_groups = i ;
				
				$scope.b_ini= angular.copy($scope.b);
			}
		
		// switch to next page
		$scope.nextPage_group = function() { 
	       nextPage_common_group($scope);
		}
		
		// switch to previous page
		$scope.previousPage_group = function() {
	      previousPage_common_group($scope);
		}
		
		 $scope.$watch('b', function() {   
			if( ($scope.page_now_group==1)  &&  ($scope.nbr_rows_groups <= $scope.entryLimit_group) )
			 {
			   $scope.disableNext_group = true;
			 }
			
		}); 
		
		 $scope.$watch('d', function() {   
			if( ($scope.page_now_eg==1)  &&  ($scope.nbr_rows_eg <= $scope.entryLimit_eg) )
			 {
			 $scope.disableNext_eg = true;
			 }
			
		}); 	
		
		// switch to next page
		$scope.nextPage_eg = function() { 
	       nextPage_evg($scope);
		}

		// switch to previous page
		$scope.previousPage_eg = function() {
	      previousPage_evg($scope);
		}
		
		 $scope.configMap = function(){
				 var mapOptions = {
				zoom: 12,
				center: new google.maps.LatLng($scope.latitude, $scope.longtitude),
				mapTypeId: google.maps.MapTypeId.TERRAIN
			   }
         
			$scope.map = new google.maps.Map(document.getElementById('map'), mapOptions);
				google.maps.event.addListener($scope.map, 'click', function(e) {
			    $scope.latitude = e.latLng.lat();
				$scope.longtitude = e.latLng.lng();
				var rad=10;
				if($scope.radius.val==1)
					rad =10;
				else
					rad =50;
				$scope.searchGroupEventNearBy(e.latLng.lng(),e.latLng.lat(),rad,0,100);
			  });
			
			$scope.markers = [];
			
			 var infoWindow = new google.maps.InfoWindow();
			 
			  var createMarker = function (info){
				
				var marker = new google.maps.Marker({
					map: $scope.map,
					position: new google.maps.LatLng(info.lat, info.long),
					title: info.name,
					icon:info.icon
				});
				marker.content = '<div class="infoWindowContent">' + info.interest + '</div>';
				
				google.maps.event.addListener(marker, 'click', function(){
					infoWindow.setContent('<h2>' + marker.title + '</h2>' + marker.content);
					infoWindow.open($scope.map, marker);
				});
				
				$scope.markers.push(marker);
				
			}
			
			
			
				 var i = 0;
				 angular.forEach($scope.cities, function(value, key) {
				   createMarker($scope.cities[i]);
				   i++;
				})
					  
			  $scope.openInfoWindow = function(e, selectedMarker){
				e.preventDefault();
				google.maps.event.trigger(selectedMarker, 'click');
			}
		 
	 };
	
}])